package com.c.ctgproject.ui.collect

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.adapter.guang.CarSearchAdapter
import com.c.ctgproject.adapter.guang.CarWeighingAdapter
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityCarSearchListBinding
import com.c.ctgproject.entity.ResultEntity
import com.c.ctgproject.entity.guang.CarListEntity
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.utils.*

/**
 *作者:LiBW
 *创建日期: 2021/10/7
 *描述: 查询车辆列表 页面
 */
class CarSearchListActivity : BaseActivityV2(),CarSearchAdapter.CarSearchCallBack{
    private val mBinding by lazy { ActivityCarSearchListBinding.inflate(layoutInflater) }
    override fun getLayout() = mBinding.root
    private val search by lazy { intent.getStringExtra(MyConstants.SEARCH).handlerNull() }
    private var page = 1
    private var mList = ArrayList<CarListEntity.DataBean.ListBean>()
    private val mAdapter by lazy { CarSearchAdapter(this, mList,this) }

    override fun onResume() {
        super.onResume()
        page = 1
        getData()
    }

    override fun event() {
        mBinding.mCarRV.adapter = mAdapter
        mBinding.mCarRV.layoutManager = LinearLayoutManager(this)
    }

    private fun getData() {
        ApiMethods.apiSubscribe(ApiMethods.retrofit.searchCar(page, search), MyObserverHandlerLoading(this, loading, mBinding.mRefresh) {
            MyLog.d("回调:$it")
            val data = getGson().fromJson(it, CarListEntity::class.java).data
            if (page == 1) mList.clear()
            data?.list?.let { list ->
                mList.addAll(list)
                mAdapter.notifyDataSetChanged()
                mBinding.mCarRV.handlerPosition(page)
            }
        })
    }

    override fun click() {
        mBinding.mRefresh.setOnLoadMoreListener {
            page++
            getData()
        }

        mBinding.mRefresh.setOnRefreshListener {
            page = 1
            getData()
        }
    }

    override fun deleteItem(position: Int, data: CarListEntity.DataBean.ListBean) {
        ApiMethods.apiSubscribe(ApiMethods.retrofit.deleteCar(data.carId), MyObserverHandlerLoading(this, loading, mBinding.mRefresh) {
            MyLog.d("删除结果:$it")
            val result= getGson().fromString<ResultEntity<String>>(it)
            if(result.status==1){
                mList.removeAt(position)
                mAdapter.notifyDataSetChanged()
            }
        })
    }
}